<template>
  <div>
    <p v-if="wsStatus === 'connected'">WebSocket connected</p>
    <p v-else-if="wsStatus === 'connecting'">WebSocket connecting...</p>
    <p v-else>WebSocket disconnected</p>
  </div>
</template>

<script>
import io from 'socket.io-client';

export default {
  data() {
    return {
      wsStatus: 'disconnected', // Possible values: 'disconnected', 'connecting', 'connected'
      ws: null
    };
  },
  methods: {
    getWxSocket() {
      this.wsStatus = 'connecting';
      this.ws = io('ws://wq.hoeagri.com:1818'); // Replace with your WebSocket server URL

      this.ws.on('connect', () => {
        console.log('WebSocket connection established');
        this.wsStatus = 'connected';
        this.ws.emit('identify', 'arrived'); // Send initial message
      });

      this.ws.on('message', (res) => {
        console.log('Message from server:', res);
      });

      this.ws.on('visitor.record.arrived', (res) => {
        console.log('Visitor record arrived:', res);
      });

      this.ws.on('pjhc1720', (res) => {
        console.log('pjhc1720 event:', res);
      });

      this.ws.on('connect_error', (error) => {
        console.log('WebSocket connection error:', error);
        this.wsStatus = 'disconnected';
        this.reconnect();
      });

      this.ws.on('connect_timeout', (timeout) => {
        console.log('WebSocket connection timeout:', timeout);
        this.wsStatus = 'disconnected';
        this.reconnect();
      });

      this.ws.on('disconnect', (reason) => {
        console.log('WebSocket disconnected:', reason);
        this.wsStatus = 'disconnected';
        this.reconnect();
      });

      this.ws.on('reconnect', (attemptNumber) => {
        console.log('WebSocket reconnecting attempt number:', attemptNumber);
        this.wsStatus = 'connecting';
        this.ws.emit('identify', 'arrived'); // Send message on reconnect
      });
    },
    reconnect() {
      console.log('Attempting to reconnect...');
      this.getWxSocket();
    }
  },
  mounted() {
    this.getWxSocket();
  }
};
</script>

<style scoped>
/* Add your component styles here */
</style>
